/*
 * Created on 2006-5-15
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package kerjodando.vincent;

import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import ants.p2p.filesharing.WarriorAnt;
import ants.p2p.gui.GuiAnt;
import ants.p2p.gui.SettingsAntPanel;
import ants.p2p.gui.FrameAnt;
import ants.p2p.query.ServerInfo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import ants.p2p.query.WebQueryFileTuple;

/**
 * @author vincent
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class getfile {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(getfile.class);

	private static String sIps = "";

	public static String getIps() {
		if (sIps.length() == 0) {
			try {
				InetAddress[] addressList = InetAddress
						.getAllByName(InetAddress.getLocalHost().getHostName());
				for (int i = 0; i < addressList.length; ++i) {
					if (!(addressList[i].isAnyLocalAddress()
							|| addressList[i].isLinkLocalAddress() || addressList[i]
							.isLoopbackAddress()
					/* || addressList[i].isSiteLocalAddress() */)) {
						if (sIps.length() != 0)
							sIps = sIps + "|";
						sIps = sIps + addressList[i].getHostAddress();
					}
				}
			} catch (Exception e) {

			}
		}
		return sIps;
	}

	public getfile() {
		logger.setLevel(Level.OFF);
		getIps();
		/*
		 * if (ants.p2p.utils.net.UPnPManager.instance().mappingsExist()) sIps =
		 * "";
		 */
	}

	private String URIString = Common.remoteDirUri;

	private ArrayList<String> prop_trustedpeers = null;

	private Properties prop_settings = null;

	public synchronized void makeSettingsFile() {
		// String Version = prop_settings.getProperty("Version");
		// String maxPullRequestsToServe = prop_settings
		// .getProperty("maxPullRequestsToServe");
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream(new File(
					WarriorAnt.workingPath + Common.settings)));
			oos.writeObject(prop_settings.getProperty("Version"));
			// System.out.println("-----"+prop_settings.getProperty("Version"));
			oos.writeInt(Integer.parseInt(prop_settings
					.getProperty("maxPullRequestsToServe")));
			// System.out.println("-----"+prop_settings.getProperty("maxPullRequestsToServe"));
			oos.writeInt(Integer.parseInt(prop_settings
					.getProperty("maxSecureConnections")));
			// System.out.println("-----"+prop_settings.getProperty("maxSecureConnections"));
			oos.writeInt(Integer.parseInt(prop_settings
					.getProperty("blockSizeInDownload")));
			// System.out.println("-----"+prop_settings.getProperty("blockSizeInDownload"));
			oos.writeInt(Integer.parseInt(prop_settings
					.getProperty("blocksPerSource")));
			// System.out.println("-----"+prop_settings.getProperty("blocksPerSource"));
			oos.writeInt(Integer.parseInt(prop_settings
					.getProperty("MaxSources")));
			// System.out.println("-----"+prop_settings.getProperty("MaxSources"));
			oos.writeObject(prop_settings.getProperty("ConnectionType"));
			oos.writeInt(Integer.parseInt(prop_settings
					.getProperty("maxNeighbours")));
			oos.writeObject(prop_settings.getProperty("downloadPath"));
			oos.writeObject(prop_settings.getProperty("chunksHome"));
			oos.writeObject(prop_settings.getProperty("lastRoutingPoint"));
			oos.writeInt(Integer.parseInt(prop_settings
					.getProperty("lastRoutingPointPort")));
			oos.writeObject(prop_settings.getProperty("ircServer"));
			oos
					.writeInt(Integer.parseInt(prop_settings
							.getProperty("ircPort")));
			oos.writeObject(prop_settings.getProperty("ircChannel"));

			oos.writeObject("casper");
			// oos.writeObject(ConnectionAntPanel.getNick());
			oos.writeBoolean(new Boolean(prop_settings
					.getProperty("autoReconnectIRC")).booleanValue());
			oos.writeBoolean(new Boolean(prop_settings
					.getProperty("searchPeersOnIRC")).booleanValue());
			oos.writeObject(prop_settings.getProperty("password"));
			oos.writeBoolean(new Boolean(prop_settings
					.getProperty("jCheckBox2.isSelected")).booleanValue());
			if (new Boolean(prop_settings.getProperty("jCheckBox2.isSelected"))
					.booleanValue()) {
				oos.writeObject(prop_settings.getProperty("LocalStringAddress")
						.trim());
			}
			oos.writeBoolean(new Boolean(prop_settings
					.getProperty("jCheckBox1.isSelected")).booleanValue());
			oos.writeBoolean(new Boolean(prop_settings
					.getProperty("autoresumeFilesOnRun")).booleanValue());
			oos.writeObject(prop_settings.getProperty("HttpServerHomePage"));
			oos.writeObject(prop_settings.getProperty("HttpServerDescription"));
			oos.writeInt(Integer.parseInt(prop_settings
					.getProperty("HttpLocalServerPort")));
			oos.writeInt(Integer.parseInt(prop_settings
					.getProperty("HttpProxyPort")));
			oos.writeBoolean(new Boolean(prop_settings
					.getProperty("HttpEnabled")).booleanValue());
			// oos.writeObject(prop_settings.getProperty("browserPath"));
			oos.writeObject("casper no need");
			oos.writeObject(prop_settings.getProperty("jTextField3.getText"));
			oos.writeInt(Integer.parseInt(prop_settings
					.getProperty("maxConcurrentDownloads")));
			oos.writeBoolean(new Boolean(prop_settings
					.getProperty("recursiveExplore")).booleanValue());
			oos.writeObject(prop_settings.getProperty("lookAndFeel"));
			oos.writeInt(Integer.parseInt(prop_settings
					.getProperty("maxRemoteDocsToTrace")));
			oos.writeBoolean(new Boolean(prop_settings
					.getProperty("monitorClipboard")).booleanValue());
			oos.writeObject(prop_settings.getProperty("currentLanguage"));
			oos.writeInt(Integer.parseInt(prop_settings
					.getProperty("bandwidthLimit")));
			oos.writeBoolean(new Boolean(prop_settings
					.getProperty("publishIpOnGWebCache")).booleanValue());
			oos.writeBoolean(new Boolean(prop_settings
					.getProperty("searchIpOnGWebCache")).booleanValue());
			oos.writeBoolean(new Boolean(prop_settings
					.getProperty("shareDownloadPath")).booleanValue());
			oos.writeBoolean(new Boolean(prop_settings.getProperty("proxied"))
					.booleanValue());
			if (new Boolean(prop_settings.getProperty("proxied"))
					.booleanValue()) {
				oos.writeObject(InetAddress.getByName(prop_settings
						.getProperty("https.proxyHost").trim()));
				oos.writeInt(Integer.parseInt(prop_settings.getProperty(
						"https.proxyPort").trim()));
			}
			oos.writeBoolean(new Boolean(prop_settings
					.getProperty("jCheckBox4.isSelected")).booleanValue());
			oos.close();
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			getfile.logger.error("makeSettingsFile()", e);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			getfile.logger.error("makeSettingsFile()", e);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			getfile.logger.error("makeSettingsFile()", e);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			getfile.logger.error("makeSettingsFile()", e);
		}
	}

	static public ArrayList<WebQueryFileTuple> downFilesList = new ArrayList<WebQueryFileTuple>();

	public synchronized void makeTrustedpeersFile() {

		ArrayList al = new ArrayList();

		String sFileName = null;
		String sHash = "";
		long lSize = 0;
		String descinfo = "";
		Iterator<String> e=prop_trustedpeers.iterator();
		boolean processfiles = false;

		while (e.hasNext()) {
			String ip = (String) e.next();
			System.out.println("ip=>" + ip);

			if ((ip != null) && (ip.length() > 0)) {
				if (ip.startsWith("__file__:")) {
					processfiles = true;
					String[] sa = ip.split(":", 5);
					if (sa.length < 5)
						continue;
					sFileName = sa[3];
					sHash = sa[2];
					descinfo = sa[4];
					try {
						lSize = Long.parseLong(sa[1]);
					} catch (Exception e2) {
						lSize = 0;
					}
					if (lSize > 0) {
						downFilesList.add(new WebQueryFileTuple(sFileName,
								sHash, lSize, descinfo));
						lSize = 0;
					}

					continue;
				}
				getfile.logger.debug(ip);
				String[] sa = ip.split(":", 4);
				if ((sa.length == 4)) {
					boolean bNeed = true;
					if (sa[3].length() > 0) {
						String[] si = sa[3].split("\\|", -1);
						for (int j = 0; j < si.length; ++j) {
							if (si[j].equals(sa[1]))
								bNeed = false;
						}
					} else {
						bNeed = false;
					}
					if (sa[0].equals(Common.identifier_id)) {
						Common.NeedSTUNT = bNeed;
						// update the outer address
						if (!sa[1].equals(Common.ipaddress)) {
							String sIpOld = Common.ipaddress;
							Common.ipaddress = sa[1];
							SettingsAntPanel sap = FrameAnt.getInstance("")
									.getGuiAnt().getConnectionAntPanel()
									.getContainer().getSettingsAntPanel();
							if (sap != null)
								sap.ReplaceNatAddress(sIpOld, Common.ipaddress);
						}
					}
					ServerInfo sInfo = new ServerInfo(sa[0], sa[1],
							new Integer((bNeed ? "-" : "") + sa[2]), sa[3]);
					// if there two ip that are the same one,then prop only hold
					// the
					// last one.
					if (!sa[0].equals(Common.identifier_id))
						al.add(sInfo);
				}

			}
		}// end of while
		ants.p2p.gui.DownloadAntPanel dap = FrameAnt.getInstance("")
				.getGuiAnt().getConnectionAntPanel().getContainer().dap;
		if (dap != null) {
			while (downFilesList.size() > 0)
				dap.createInterruptedDownload(downFilesList.remove(0));
		}
		try {
			ObjectOutputStream oos = new ObjectOutputStream(
					new FileOutputStream(WarriorAnt.workingPath
							+ Common.trustedpeers));
			oos.writeObject(al);
			oos.close();
		} catch (IOException ee) {
			getfile.logger.error("Cannot store trusted peers", ee);
		}
	}

	public synchronized boolean downloadFiles() {
		InternetFile ifThread = new InternetFile();
		// for (int i = 0; i < files_name.size(); i++) {
		// files_name.get(i)==>Common.trustedpeers
		ifThread.SetURL(getURIString() + Common.trustedpeers);

		System.out.println("-" + Common.trustedpeers + "-");
		// if (((String) files_name.get(i)).endsWith(".ant")) {

		String port = FrameAnt.getInstance("").getGuiAnt()
				.getConnectionAntPanel().getPort();
		Common.port = port;
		if (ifThread.GetURLFile_Settings(getURIString() + Common.trustedpeers
				+ "?ver=1&port=" + port + ":" + sIps + "&identifier="
				+ Common.identifier_id,true)) {
			// successfully get trustedpeers
			prop_trustedpeers = ifThread.getPropArrayList();
		} else {
			getfile.logger.error("no find =>" + Common.trustedpeers);
		}

		return true;
	}

	/**
	 * @return Returns the uRIString.
	 */
	public String getURIString() {
		if (!URIString.endsWith("/")) {
			URIString = URIString + "/";
		}
		return URIString;
	}

	/**
	 * @param string
	 *            The uRIString to set.
	 */
	public void setURIString(String string) {
		URIString = string;
	}

}